﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Swift;

public enum ConnectionType
{
    None    = 0,

    OnTopFixX    = 0x0100, // 在上方，固定 x 轴
    OnBottomFixX = 0x0200, // 在下方，固定 x 轴
    OnLeftFixY   = 0x0400, // 在左边，固定 y 轴
    OnRightFixY  = 0x0800, // 在右边，固定 y 轴

    Concentric  = 0x0001, // 同轴，传递角速度
    Clenching   = 0x0002, // 啮合，传递线速度和位移
}

public interface IAngularVelocityDeliever
{
    float AngularDelta { get; }
}

public interface ILinearVelocityDeliever
{
    float LinearDelta(float angle);
}

public abstract class Unit : SerializableData
{
    public string Name;
    public Vector2 Pos = Vector2.zero;
    public float Angle = 0;

    public Unit Src { get; private set; }
    public Dictionary<Unit, ConnectionType> Dst = new Dictionary<Unit, ConnectionType>();

    protected override void Sync()
    {
        BeginSync();
        SyncString(ref Name);
        SyncFloat(ref Pos.x);
        SyncFloat(ref Pos.y);
        SyncFloat(ref Angle);
        EndSync();
    }

    public Unit[] AllChildren
    {
        get { return Dst.Keys.ToArray(); }
    }

    public void LinkChild(Unit dst, ConnectionType ct)
    {
        Dst[dst] = ct;
        dst.Src = this;
    }

    public void UnlinkChild(Unit dst)
    {
        Dst.Remove(dst);
        dst.Src = null;
    }

    public ConnectionType GetLinkType(Unit dst)
    {
        return Dst[dst];
    }

    public bool HasChildren(Unit u)
    {
        foreach (var dst in Dst.Keys)
        {
            if (dst == u || dst.HasChildren(u))
                return true;
        }

        return false;
    }

    public virtual Vector2 PositionOffset(float angle)
    {
        return Vector2.zero;
    }

    public abstract void UpdateSelf(float te, ConnectionType dt);
    public void Update(float te, ConnectionType ct)
    {
        UpdateSelf(te, ct);
        UpdateAllChildren(te);
    }

    public void UpdateAllChildren(float te)
    {
        foreach (var d in Dst.Keys)
            d.Update(te, Dst[d]);
    }
}
